<?php

declare(strict_types=1);

/**
 * @charset UTF-8
 */

namespace app\admin\controller;

use app\common\controller\BaseController;
use app\common\utils\JsonResponse;
use app\common\library\CommandExecutor;
use think\App;

class Monitor extends BaseController
{
    private $executor;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->executor = new CommandExecutor();
    }

    /**
     * 获取系统基础信息
     * @return JsonResponse
     * @permission monitor:system:info
     */
    public function getSystemInfo()
    {
        $info = [];

        if (PHP_OS_FAMILY === 'Linux') {
            $info = $this->getLinuxSystemInfo();
        } elseif (PHP_OS_FAMILY === 'Windows') {
            $info = $this->getWindowsSystemInfo();
        }

        return JsonResponse::success(['system' => $info]);
    }

    /**
     * 获取主板信息
     * @return JsonResponse
     * @permission monitor:motherboard:info
     */
    public function getMotherboardInfo()
    {
        $info = [];

        if (PHP_OS_FAMILY === 'Linux') {
            $result = $this->executor->executeLinux('dmidecode -t baseboard');
            if ($result['code'] === 0) {
                preg_match('/Manufacturer: (.+)/', $result['output'], $manufacturer);
                preg_match('/Product Name: (.+)/', $result['output'], $product);
                preg_match('/Serial Number: (.+)/', $result['output'], $serial);
                preg_match('/Version: (.+)/', $result['output'], $version);
                preg_match('/Status: (.+)/', $result['output'], $status);
                preg_match('/Asset Tag: (.+)/', $result['output'], $tag);

                $info = [
                    'manufacturer' => trim($manufacturer[1] ?? '未知'),
                    'model' => trim($product[1] ?? '未知'),
                    'serial' => trim($serial[1] ?? '未知'),
                    'version' => trim($version[1] ?? '未知'),
                    'status' => trim($status[1] ?? 'OK'),
                    'tag' => trim($tag[1] ?? '未知')
                ];
            }
        } elseif (PHP_OS_FAMILY === 'Windows') {
            $result = $this->executor->executePowerShell('Get-WmiObject -Class Win32_BaseBoard | Select-Object Manufacturer,Product,SerialNumber,Version,Status,Tag | ConvertTo-Json');
            if ($result['code'] === 0) {
                $motherboard = json_decode($result['output'], true);
                if ($motherboard) {
                    $info = [
                        'manufacturer' => $motherboard['Manufacturer'] ?? '未知', // 制造商
                        'model' => $motherboard['Product'] ?? '未知', // 型号
                        'serial' => $motherboard['SerialNumber'] ?? '未知', // 序列号
                        'version' => $motherboard['Version'] ?? '未知', // 版本
                        'status' => $motherboard['Status'] ?? '未知', // 工作状态
                        'tag' => $motherboard['Tag'] ?? '未知', // 标识符
                    ];
                }
            }
        }

        return JsonResponse::success(['motherboard' => $info]);
    }

    /**
     * 获取CPU信息
     * @return JsonResponse
     * @permission monitor:cpu:info
     */
    public function getCpuInfo()
    {
        $info = [];

        if (PHP_OS_FAMILY === 'Linux') {
            $result = $this->executor->executeLinux('cat /proc/cpuinfo');
            if ($result['code'] === 0) {
                preg_match('/model name\s+:\s+(.+)/', $result['output'], $model);
                preg_match('/vendor_id\s+:\s+(.+)/', $result['output'], $vendor);
                preg_match('/cpu MHz\s+:\s+(.+)/', $result['output'], $mhz);
                preg_match_all('/processor\s+:\s+\d+/', $result['output'], $cores);
                preg_match('/cache size\s+:\s+(.+)/', $result['output'], $cache);
                preg_match('/physical id\s+:\s+(.+)/', $result['output'], $processorId);
                preg_match('/cpu family\s+:\s+(.+)/', $result['output'], $family);

                // 获取CPU使用率
                $usage = $this->executor->executeLinux("top -bn1 | grep 'Cpu(s)' | awk '{print $2}'");

                // 获取CPU最大频率
                $maxFreq = $this->executor->executeLinux("cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq");
                $maxMhz = $maxFreq['code'] === 0 ? round(intval(trim($maxFreq['output'])) / 1000, 0) : 0;

                // 获取CPU电压（如果可用）
                $voltage = $this->executor->executeLinux("cat /sys/class/power_supply/BAT0/voltage_now");
                $voltageValue = $voltage['code'] === 0 ? round(intval(trim($voltage['output'])) / 1000000, 1) : 0;

                // 获取CPU架构
                $arch = $this->executor->executeLinux("uname -m");

                $info = [
                    'name' => trim($model[1] ?? '未知'),
                    'manufacturer' => trim($vendor[1] ?? '未知'),
                    'clock_speed' => round(floatval(trim($mhz[1] ?? 0)), 0) . ' MHz',
                    'max_clock_speed' => $maxMhz . ' MHz',
                    'cores' => count($cores[0] ?? []),
                    'threads' => count($cores[0] ?? []) * 2, // 假设每个核心有2个线程
                    'l2_cache' => '0 MB', // Linux 可能需要额外命令获取
                    'l3_cache' => trim($cache[1] ?? '0 MB'),
                    'usage' => trim($usage['output'] ?? '0') . '%',
                    'voltage' => $voltageValue . ' V',
                    'processor_id' => trim($processorId[1] ?? '未知'),
                    'socket' => 'CPU ' . (trim($processorId[1] ?? '0')),
                    'status' => 'OK',
                    'architecture' => trim($arch['output'] ?? 'x86_64'),
                    'description' => trim($model[1] ?? '未知'),
                    'family' => trim($family[1] ?? '未知'),
                    'data_width' => '64 位',
                    'address_width' => '64 位'
                ];

                // 尝试获取L2缓存信息
                $l2Result = $this->executor->executeLinux("getconf LEVEL2_CACHE_SIZE");
                if ($l2Result['code'] === 0) {
                    $info['l2_cache'] = round(intval(trim($l2Result['output'])) / 1024, 0) . ' MB';
                }
            }
        } elseif (PHP_OS_FAMILY === 'Windows') {
            $result = $this->executor->executePowerShell('Get-WmiObject -Class Win32_Processor | Select-Object Name,Manufacturer,CurrentClockSpeed,MaxClockSpeed,NumberOfCores,NumberOfLogicalProcessors,L2CacheSize,L3CacheSize,LoadPercentage,ThreadCount,CurrentVoltage,ProcessorId,SocketDesignation,Status,Architecture,Description,Family,DataWidth,AddressWidth | ConvertTo-Json');
            if ($result['code'] === 0) {
                $cpu = json_decode($result['output'], true);
                if ($cpu) {
                    $info = [
                        'name' => trim($cpu['Name'] ?? '未知'), // CPU型号
                        'manufacturer' => trim($cpu['Manufacturer'] ?? '未知'), // 制造商
                        'clock_speed' => ($cpu['CurrentClockSpeed'] ?? 0) . ' MHz', // 当前频率
                        'max_clock_speed' => ($cpu['MaxClockSpeed'] ?? 0) . ' MHz', // 最大频率
                        'cores' => $cpu['NumberOfCores'] ?? 0, // 物理核心数
                        'threads' => $cpu['ThreadCount'] ?? $cpu['NumberOfLogicalProcessors'] ?? 0, // 线程数
                        'l2_cache' => round(($cpu['L2CacheSize'] ?? 0) / 1024, 2) . ' MB', // L2缓存
                        'l3_cache' => round(($cpu['L3CacheSize'] ?? 0) / 1024, 2) . ' MB', // L3缓存
                        'usage' => ($cpu['LoadPercentage'] ?? 0) . '%', // CPU使用率
                        'voltage' => ($cpu['CurrentVoltage'] ?? 0) / 10 . ' V', // 电压
                        'processor_id' => $cpu['ProcessorId'] ?? '未知', // 处理器ID
                        'socket' => $cpu['SocketDesignation'] ?? '未知', // CPU插槽
                        'status' => $cpu['Status'] ?? '未知', // 工作状态
                        'architecture' => $this->getCpuArchitecture($cpu['Architecture'] ?? null), // CPU架构
                        'description' => $cpu['Description'] ?? '未知', // 描述
                        'family' => $cpu['Family'] ?? '未知', // CPU系列
                        'data_width' => ($cpu['DataWidth'] ?? 0) . ' 位', // 数据宽度
                        'address_width' => ($cpu['AddressWidth'] ?? 0) . ' 位' // 地址宽度
                    ];
                }
            }
        }

        return JsonResponse::success(['cpu' => $info]);
    }

    /**
     * 获取内存信息
     * @return JsonResponse
     * @permission monitor:memory:info
     */
    public function getMemoryInfo()
    {
        $info = [];


        // 内存类型映射
        $memoryTypes = [
            0 => '未知',
            1 => '其他',
            2 => 'DRAM',
            3 => '同步DRAM',
            4 => '缓存DRAM',
            5 => 'EDO',
            6 => 'EDRAM',
            7 => 'VRAM',
            8 => 'SRAM',
            9 => 'RAM',
            10 => 'ROM',
            11 => 'Flash',
            12 => 'EEPROM',
            13 => 'FEPROM',
            14 => 'EPROM',
            15 => 'CDRAM',
            16 => '3DRAM',
            17 => 'SDRAM',
            18 => 'SGRAM',
            19 => 'RDRAM',
            20 => 'DDR',
            21 => 'DDR2',
            22 => 'DDR2 FB-DIMM',
            24 => 'DDR3',
            26 => 'DDR4',
            27 => 'DDR5'
        ];

        // 内存条类型映射
        $formFactors = [
            0 => '未知',
            1 => '其他',
            2 => 'SIP',
            3 => 'DIP',
            4 => 'ZIP',
            5 => 'SOJ',
            6 => '专有',
            7 => 'SIMM',
            8 => 'DIMM',
            9 => 'TSOP',
            10 => 'PGA',
            11 => 'RIMM',
            12 => 'SODIMM',
            13 => 'SRIMM',
            14 => 'SMD',
            15 => 'SSMP',
            16 => 'QFP',
            17 => 'TQFP',
            18 => 'SOIC',
            19 => 'LCC',
            20 => 'PLCC',
            21 => 'BGA',
            22 => 'FPBGA',
            23 => 'LGA'
        ];

        if (PHP_OS_FAMILY === 'Linux') {
            // 获取内存总体信息
            $result = $this->executor->executeLinux('free -b');
            if ($result['code'] === 0) {
                preg_match('/Mem:\s+(\d+)\s+\d+\s+(\d+)/', $result['output'], $matches);
                $total = round(($matches[1] ?? 0) / 1024 / 1024 / 1024, 2);
                $available = round(($matches[2] ?? 0) / 1024 / 1024 / 1024, 2);
                $used = $total - $available;
                $usage = $total > 0 ? round(($used / $total) * 100, 2) : 0;

                // 获取内存模块详细信息
                $modules = [];
                $moduleInfo = $this->executor->executeLinux('dmidecode -t memory');
                if ($moduleInfo['code'] === 0) {
                    preg_match_all('/Size: (.+)[\s\S]+?Type: (.+)[\s\S]+?Speed: (.+)[\s\S]+?Manufacturer: (.+)[\s\S]+?Serial Number: (.+)[\s\S]+?Bank Locator: (.+)[\s\S]+?Part Number: (.+)[\s\S]+?Form Factor: (.+)/m', $moduleInfo['output'], $memMatches, PREG_SET_ORDER);
                    foreach ($memMatches as $match) {
                        if (strpos($match[1], 'No Module Installed') === false) {
                            $modules[] = [
                                'manufacturer' => trim($match[4] ?? '未知'),
                                'capacity' => trim($match[1] ?? '未知'),
                                'speed' => trim($match[3] ?? '未知'),
                                'slot' => trim($match[6] ?? '未知'),
                                'part_number' => trim($match[7] ?? '未知'),
                                'serial_number' => trim($match[5] ?? '未知'),
                                'form_factor' => $formFactors[$match[8] ?? 0] ?? '未知',
                                'memory_type' => $memoryTypes[$match[2] ?? 0] ?? '未知',
                                'bank_label' => trim($match[6] ?? '未知'),
                                'type_detail' => '未知'
                            ];
                        }
                    }
                }

                $info = [
                    'modules' => $modules,
                    'total' => $total . ' GB',
                    'available' => $available . ' GB',
                    'usage' => $usage . '%'
                ];
            }
        } elseif (PHP_OS_FAMILY === 'Windows') {
            $result = $this->executor->executePowerShell('Get-WmiObject -Class Win32_PhysicalMemory | Select-Object Manufacturer,Capacity,Speed,DeviceLocator,PartNumber,SerialNumber,FormFactor,MemoryType,TypeDetail,BankLabel | ConvertTo-Json');
            if ($result['code'] === 0) {
                $memoryModules = json_decode($result['output'], true) ?? [];
                $totalMemory = 0;
                $info = [
                    'modules' => [],
                    'total' => '0 GB',
                    'available' => '0 GB',
                    'usage' => '0%'
                ];

                if (!is_array($memoryModules)) {
                    $memoryModules = [$memoryModules];
                }

                foreach ($memoryModules as $module) {
                    $totalMemory += $module['Capacity'] ?? 0;
                    $info['modules'][] = [
                        'manufacturer' => $module['Manufacturer'] ?? '未知', // 制造商
                        'capacity' => round(($module['Capacity'] ?? 0) / 1024 / 1024 / 1024, 2) . ' GB', // 容量
                        'speed' => ($module['Speed'] ?? 0) . ' MHz', // 速度
                        'slot' => $module['DeviceLocator'] ?? '未知', // 插槽
                        'part_number' => $module['PartNumber'] ?? '未知', // 型号
                        'serial_number' => $module['SerialNumber'] ?? '未知', // 序列号
                        'form_factor' => $formFactors[$module['FormFactor'] ?? 0] ?? '未知', // 内存条类型
                        'memory_type' => $memoryTypes[$module['MemoryType'] ?? 0] ?? '未知', // 内存类型
                        'bank_label' => $module['BankLabel'] ?? '未知', // 内存通
                        'type_detail' => $module['TypeDetail'] ?? '未知' // 详细类型
                    ];
                }

                $info['total'] = round($totalMemory / 1024 / 1024 / 1024) . ' GB'; // 总内存

                // 获取可用内存和内存使用率
                $result = $this->executor->executePowerShell('(Get-WmiObject -Class Win32_OperatingSystem).FreePhysicalMemory');
                if ($result['code'] === 0) {
                    $availableKB = floatval(trim($result['output']));
                    $info['available'] = round($availableKB / 1024 / 1024, 2) . ' GB';
                    // 计算内存使用率
                    $info['usage'] = $totalMemory > 0 ?
                        round(($totalMemory - ($availableKB * 1024)) / $totalMemory * 100, 2) . '%' :
                        '0%';
                }
            }
        }

        return JsonResponse::success(['memory' => $info]);
    }

    /**
     * 获取磁盘信息
     * @return JsonResponse
     * @permission monitor:disk:info
     */
    public function getDiskInfo()
    {
        $info = [];

        if (PHP_OS_FAMILY === 'Linux') {
            $result = $this->executor->executeLinux('df -B1');
            if ($result['code'] === 0) {
                $lines = explode("\n", trim($result['output']));
                array_shift($lines); // 移除标题行

                $disks = [];
                foreach ($lines as $line) {
                    $parts = preg_split('/\s+/', $line);
                    if (count($parts) >= 6) {
                        $size = round($parts[1] / 1024 / 1024 / 1024, 2);
                        $used = round($parts[2] / 1024 / 1024 / 1024, 2);
                        $free = round($parts[3] / 1024 / 1024 / 1024, 2);
                        $usage = round(($used / $size) * 100, 2);

                        // 获取文件系统类型和标签
                        $fsInfo = $this->executor->executeLinux("blkid " . $parts[0]);
                        preg_match('/TYPE="([^"]+)"/', $fsInfo['output'], $fsType);
                        preg_match('/LABEL="([^"]+)"/', $fsInfo['output'], $fsLabel);

                        $disks[] = [
                            'drive' => $parts[5],
                            'size' => $size . ' GB',
                            'free_space' => $free . ' GB',
                            'used_space' => $used . ' GB',
                            'usage' => $usage . '%',
                            'type' => 3, // 固定磁盘
                            'file_system' => trim($fsType[1] ?? $parts[0]),
                            'label' => trim($fsLabel[1] ?? '')
                        ];
                    }
                }
                $info = $disks;
            }
        } elseif (PHP_OS_FAMILY === 'Windows') {
            $diskCommand = 'Get-WmiObject -Class Win32_LogicalDisk | ForEach-Object { @{ Drive = $_.DeviceID; Size = [math]::Round($_.Size/1GB, 2); FreeSpace = [math]::Round($_.FreeSpace/1GB, 2); Type = $_.DriveType; FileSystem = $_.FileSystem; Label = $_.VolumeName } } | ConvertTo-Json';
            $result = $this->executor->executePowerShell($diskCommand);
            if ($result['code'] === 0) {
                $disks = json_decode($result['output'], true) ?? [];
                if (!is_array($disks)) {
                    $disks = [$disks];
                }

                $info = array_map(function ($disk) {
                    $size = $disk['Size'] ?? 0;
                    $freeSpace = $disk['FreeSpace'] ?? 0;
                    $usedSpace = $size - $freeSpace;
                    $usage = $size > 0 ? round(($usedSpace / $size) * 100, 2) : 0;

                    return [
                        'drive' => $disk['Drive'] ?? '未知',
                        'size' => $size . ' GB',
                        'free_space' => $freeSpace . ' GB',
                        'used_space' => round($usedSpace, 2) . ' GB',
                        'usage' => $usage . '%',
                        'type' => $disk['Type'] ?? '未知',
                        'file_system' => $disk['FileSystem'] ?? '未知',
                        'label' => $disk['Label'] ?? '未知'
                    ];
                }, $disks);
            }
        }

        return JsonResponse::success(['disks' => $info]);
    }

    /**
     * 获取显卡信息
     * @return JsonResponse
     * @permission monitor:gpu:info
     */
    public function getGpuInfo()
    {
        $info = [];

        if (PHP_OS_FAMILY === 'Linux') {
            $gpus = [];

            // 获取显卡基本信息
            $result = $this->executor->executeLinux('lspci -v | grep -A 10 VGA');
            if ($result['code'] === 0) {
                preg_match_all('/VGA.*: (.+)[\s\S]+?Memory.*: ([^\n]+)/', $result['output'], $matches, PREG_SET_ORDER);

                foreach ($matches as $match) {
                    // 获取显卡驱动信息
                    $driverInfo = $this->executor->executeLinux('glxinfo | grep "OpenGL version"');
                    preg_match('/OpenGL version string: (.+)/', $driverInfo['output'], $driver);

                    // 获取分辨率和刷新率
                    $displayInfo = $this->executor->executeLinux('xrandr | grep " connected"');
                    preg_match('/(\d+x\d+)\s+(\d+\.\d+)\*/', $displayInfo['output'], $display);

                    $gpus[] = [
                        'name' => trim($match[1] ?? '未知'),
                        'memory' => trim($match[2] ?? '未知'),
                        'driver' => trim($driver[1] ?? '未知'),
                        'processor' => trim($match[1] ?? '未知'),
                        'memory_type' => 'GDDR',
                        'refresh_rate' => trim($display[2] ?? '60') . ' Hz',
                        'resolution' => trim($display[1] ?? '1920x1080'),
                        'status' => 'OK',
                        'architecture' => 'Unknown',
                        'max_refresh_rate' => trim($display[2] ?? '60') . ' Hz',
                        'min_refresh_rate' => '60 Hz',
                        'installed_drivers' => trim($driver[1] ?? '未知')
                    ];
                }
            }

            $info = $gpus;
        } elseif (PHP_OS_FAMILY === 'Windows') {
            $result = $this->executor->executePowerShell('Get-WmiObject -Class Win32_VideoController | Select-Object Name,AdapterRAM,DriverVersion,VideoProcessor,CurrentRefreshRate,CurrentHorizontalResolution,CurrentVerticalResolution,Status,VideoArchitecture,VideoMemoryType,MaxRefreshRate,MinRefreshRate,InstalledDisplayDrivers | ConvertTo-Json');
            if ($result['code'] === 0) {
                $gpuInfo = json_decode($result['output'], true) ?? [];
                if (!is_array($gpuInfo)) {
                    $gpuInfo = [$gpuInfo];
                }

                $info = array_map(function ($gpu) {
                    $memoryTypes = [
                        1 => '其他',
                        2 => '未知',
                        3 => 'VRAM',
                        4 => 'DRAM',
                        5 => 'SRAM',
                        6 => 'WRAM',
                        7 => 'EDO RAM',
                        8 => '板载 RAM',
                        9 => 'SDRAM',
                        10 => 'SGRAM'
                    ];

                    $videoArchitectures = [
                        1 => 'Other',
                        2 => 'Unknown',
                        3 => 'CGA',
                        4 => 'EGA',
                        5 => 'VGA',
                        6 => 'SVGA',
                        7 => 'MDA',
                        8 => 'HGC',
                        9 => 'MCGA',
                        10 => '8514A',
                        11 => 'XGA',
                        12 => 'Linear Frame Buffer',
                        160 => 'PC-98'
                    ];

                    return [
                        'name' => $gpu['Name'] ?? '未知',
                        'memory' => round(($gpu['AdapterRAM'] ?? 0) / 1024 / 1024 / 1024, 2) . ' GB',
                        'driver' => $gpu['DriverVersion'] ?? '未知',
                        'processor' => $gpu['VideoProcessor'] ?? '未知',
                        'memory_type' => $memoryTypes[$gpu['VideoMemoryType'] ?? 0] ?? '未知',
                        'refresh_rate' => ($gpu['CurrentRefreshRate'] ?? 0) . ' Hz',
                        'resolution' => ($gpu['CurrentHorizontalResolution'] ?? 0) . 'x' . ($gpu['CurrentVerticalResolution'] ?? 0),
                        'status' => $gpu['Status'] ?? '未知',
                        'architecture' => $videoArchitectures[$gpu['VideoArchitecture'] ?? 0] ?? '未知',
                        'max_refresh_rate' => ($gpu['MaxRefreshRate'] ?? 0) . ' Hz',
                        'min_refresh_rate' => ($gpu['MinRefreshRate'] ?? 0) . ' Hz',
                        'installed_drivers' => $gpu['InstalledDisplayDrivers'] ?? '未知'
                    ];
                }, $gpuInfo);
            }
        }

        return JsonResponse::success(['gpu' => $info]);
    }

    /**
     * 获取服务监控信息
     * @return JsonResponse
     * @permission monitor:service:info
     */
    public function getServiceInfo()
    {
        $services = [];

        if (PHP_OS_FAMILY === 'Linux') {
            // 获取Nginx信息
            $nginx = $this->getLinuxServiceInfo('nginx');
            if ($nginx) {
                $services[] = $nginx;
            }

            // 获取MySQL信息
            $mysql = $this->getLinuxServiceInfo('mysql');
            if ($mysql) {
                $services[] = $mysql;
            }

            // 获取PHP-FPM信息
            $phpfpm = $this->getLinuxServiceInfo('php-fpm');
            if ($phpfpm) {
                $services[] = $phpfpm;
            }

            // 获取Redis信息
            $redis = $this->getLinuxServiceInfo('redis');
            if ($redis) {
                $services[] = $redis;
            }
        } elseif (PHP_OS_FAMILY === 'Windows') {
            // 获取Windows服务信息
            $services = $this->getWindowsServicesInfo();
        }

        return JsonResponse::success(['services' => $services]);
    }

    /**
     * 获取Linux服务信息
     * @param string $service 服务名称
     * @return array|null
     */
    private function getLinuxServiceInfo(string $service): ?array
    {
        $info = [
            'name' => ucfirst($service),
            'status' => 'stopped',
            'version' => '未知',
            'port' => 0,
            'pid' => 0,
            'uptime' => '0分钟'
        ];

        // 检查服务状态
        $status = $this->executor->executeLinux("systemctl is-active $service");
        if ($status['code'] === 0 && trim($status['output']) === 'active') {
            $info['status'] = 'running';

            // 获取PID
            $pid = $this->executor->executeLinux("systemctl show -p MainPID $service");
            if ($pid['code'] === 0) {
                preg_match('/MainPID=(\d+)/', $pid['output'], $matches);
                $info['pid'] = intval($matches[1] ?? 0);
            }

            // 获取运行时间
            if ($info['pid'] > 0) {
                $uptime = $this->executor->executeLinux("ps -o etime= -p " . $info['pid']);
                if ($uptime['code'] === 0) {
                    $info['uptime'] = trim($uptime['output']);
                }
            }

            // 获取版本信息
            switch ($service) {
                case 'nginx':
                    $version = $this->executor->executeLinux('nginx -v 2>&1');
                    if ($version['code'] === 0) {
                        preg_match('/nginx\/(\d+\.\d+\.\d+)/', $version['output'], $matches);
                        $info['version'] = $matches[1] ?? '未知';
                    }
                    $info['port'] = 80;
                    break;

                case 'mysql':
                    $version = $this->executor->executeLinux('mysql -V');
                    if ($version['code'] === 0) {
                        preg_match('/Distrib (\d+\.\d+\.\d+)/', $version['output'], $matches);
                        $info['version'] = $matches[1] ?? '未知';
                    }
                    $info['port'] = 3306;
                    break;

                case 'php-fpm':
                    $version = $this->executor->executeLinux('php-fpm -v');
                    if ($version['code'] === 0) {
                        preg_match('/PHP (\d+\.\d+\.\d+)/', $version['output'], $matches);
                        $info['version'] = $matches[1] ?? '未知';
                    }
                    $info['port'] = 9000;
                    break;

                case 'redis':
                    $version = $this->executor->executeLinux('redis-server -v');
                    if ($version['code'] === 0) {
                        preg_match('/v=(\d+\.\d+\.\d+)/', $version['output'], $matches);
                        $info['version'] = $matches[1] ?? '未知';
                    }
                    $info['port'] = 6379;
                    break;
            }

            return $info;
        }

        return null;
    }

    /**
     * 获取Windows服务信息
     * @return array
     */
    private function getWindowsServicesInfo(): array
    {
        $services = [];
        $serviceConfigs = [
            'nginx' => [
                'processName' => env('NGINX_PROCESS_NAME', 'nginx'),
                'port' => env('NGINX_PORT', 80),
                'versionCmd' => env('NGINX_VERSION_CMD'),
                'versionRegex' => env('NGINX_VERSION_REGEX')
            ],
            'mysql' => [
                'processName' => env('MYSQL_PROCESS_NAME', 'mysqld'),
                'port' => env('MYSQL_PORT', 3306), 
                'versionCmd' => env('MYSQL_VERSION_CMD'),
                'versionRegex' => env('MYSQL_VERSION_REGEX')
            ],
            'php' => [
                'processName' => env('PHP_PROCESS_NAME', 'php-cgi'),
                'port' => env('PHP_PORT', 9000),
                'versionCmd' => env('PHP_VERSION_CMD'),
                'versionRegex' => env('PHP_VERSION_REGEX')
            ],
            'redis' => [
                'processName' => env('REDIS_PROCESS_NAME', 'redis-server'),
                'port' => env('REDIS_PORT', 6379),
                'versionCmd' => env('REDIS_VERSION_CMD'),
                'versionRegex' => env('REDIS_VERSION_REGEX')
            ]
        ];

        foreach ($serviceConfigs as $key => $config) {
            // 检查进程是否运行
            $processResult = $this->executor->executePowerShell("Get-Process -Name '{$config['processName']}' -ErrorAction SilentlyContinue | Select-Object Id,StartTime,CPU,WorkingSet | ConvertTo-Json");

            if ($processResult['code'] === 0) {
                $processInfo = json_decode($processResult['output'], true);
                
                // 获取版本信息
                $versionResult = $this->executor->executePowerShell($config['versionCmd']);

                if ($versionResult['code'] === 0) {
                    preg_match($config['versionRegex'], $versionResult['output'], $matches);
                    $version = $matches[1] ?? '未知';
                } else {
                    $version = '未知';
                }

                $services[] = [
                    'name' => $config['processName'],
                    'port' => $config['port'],
                    'version' => $version,
                    'pid' => $processInfo['Id'] ?? 0,
                    'memory' => isset($processInfo['WorkingSet']) ? round($processInfo['WorkingSet'] / 1024 / 1024, 2) . ' MB' : '0 MB',
                    'cpu' => isset($processInfo['CPU']) ? round($processInfo['CPU'], 2) . '%' : '0%'
                ];
            }else{
                $services[] = [
                    'name' => $config['processName'],
                    'port' => $config['port'],
                    'version' => '未知',
                    'pid' => 0,
                    'memory' => '0 MB',
                    'cpu' => '0%'
                ];
            }
        }

        return $services;
    }

    /**
     * 获取Linux系统基本信息
     * @return array
     */
    private function getLinuxSystemInfo(): array
    {
        $info = [];

        // 获取操作系统信息
        $result = $this->executor->executeLinux('cat /etc/os-release');
        if ($result['code'] === 0) {
            preg_match('/PRETTY_NAME="(.+)"/', $result['output'], $matches);
            // 获取系统架构
            $archResult = $this->executor->executeLinux('uname -m');
            $arch = trim($archResult['output'] ?? '');
            $info['os_version'] = ($matches[1] ?? '未知') . ' ' . $arch;
        }

        // 获取系统版本号
        $result = $this->executor->executeLinux('uname -r');
        if ($result['code'] === 0) {
            $info['os_build'] = trim($result['output']);
        }

        // 获取系统启动时间
        $result = $this->executor->executeLinux('uptime -s');
        if ($result['code'] === 0) {
            $info['boot_time'] = str_replace(['-', ' ', ':'], '', trim($result['output'])) . '.000000+480';
        }

        // 获取当前登录用户
        $result = $this->executor->executeLinux('whoami');
        if ($result['code'] === 0) {
            $info['registered_user'] = trim($result['output']);
        }

        // 取主机名作为序列号
        $result = $this->executor->executeLinux('hostnamectl');
        if ($result['code'] === 0) {
            preg_match('/Machine ID: (.+)/', $result['output'], $matches);
            $info['serial_number'] = trim($matches[1] ?? '未知');
        }

        // 获取制造商信息
        $result = $this->executor->executeLinux('dmidecode -t system');
        if ($result['code'] === 0) {
            preg_match('/Manufacturer: (.+)/', $result['output'], $matches);
            $info['manufacturer'] = trim($matches[1] ?? '未知');
        }

        // 组织信息（Linux下可能没有，设置默认值）
        $info['organization'] = '';

        // 获取系统安装时间（使用根目录的创建时间���为近似值）
        $result = $this->executor->executeLinux('stat -c %w /');
        if ($result['code'] === 0) {
            $installDate = trim($result['output']);
            if ($installDate) {
                $info['install_date'] = str_replace(['-', ' ', ':'], '', $installDate) . '.000000+480';
            } else {
                $info['install_date'] = '未知';
            }
        }

        // 获取当前时间
        $info['local_time'] = date('YmdHis') . '.000000+480';

        // 获取进程数量
        $result = $this->executor->executeLinux('ps aux | wc -l');
        if ($result['code'] === 0) {
            $info['process_count'] = intval(trim($result['output'])) - 1; // 减去标题行
        }

        // 获取当前登录用户数
        $result = $this->executor->executeLinux('who | wc -l');
        if ($result['code'] === 0) {
            $info['user_count'] = intval(trim($result['output']));
        }

        // 获取内存使用情况
        $result = $this->executor->executeLinux('free -b');
        if ($result['code'] === 0) {
            preg_match('/Mem:\s+(\d+)\s+(\d+)\s+(\d+)/', $result['output'], $matches);
            if (isset($matches[1])) {
                $total = $matches[1] / 1024 / 1024 / 1024; // 转换为GB
                $used = ($matches[1] - $matches[3]) / 1024 / 1024 / 1024;
                $free = $matches[3] / 1024 / 1024 / 1024;
                $usage = $total > 0 ? ($used / $total) * 100 : 0;

                $info['memory_usage'] = [
                    'total' => round($total, 2) . ' GB',
                    'used' => round($used, 2) . ' GB',
                    'free' => round($free, 2) . ' GB',
                    'usage' => round($usage, 2) . '%'
                ];
            }

            // 获取虚拟内存（swap）信息
            preg_match('/Swap:\s+(\d+)\s+(\d+)\s+(\d+)/', $result['output'], $matches);
            if (isset($matches[1])) {
                $total = $matches[1] / 1024 / 1024 / 1024;
                $used = ($matches[1] - $matches[3]) / 1024 / 1024 / 1024;
                $free = $matches[3] / 1024 / 1024 / 1024;
                $usage = $total > 0 ? ($used / $total) * 100 : 0;

                $info['virtual_memory_usage'] = [
                    'total' => round($total, 2) . ' GB',
                    'used' => round($used, 2) . ' GB',
                    'free' => round($free, 2) . ' GB',
                    'usage' => round($usage, 2) . '%'
                ];
            }
        }

        return $info;
    }

    /**
     * 获取Windows系统基本信息
     * @return array
     */
    private function getWindowsSystemInfo(): array
    {
        $info = [];

        // 获取系统信息
        $result = $this->executor->executePowerShell('Get-WmiObject -class Win32_OperatingSystem | Select-Object Caption,Version,BuildNumber,OSArchitecture,LastBootUpTime,RegisteredUser,SerialNumber,Manufacturer,Organization,InstallDate,LocalDateTime,NumberOfProcesses,NumberOfUsers,TotalVisibleMemorySize,FreePhysicalMemory,TotalVirtualMemorySize,FreeVirtualMemory | ConvertTo-Json');
        if ($result['code'] === 0) {
            $systemInfo = json_decode($result['output'], true);
            if ($systemInfo) {
                $info['os_version'] = trim($systemInfo['Caption'] ?? '未知') . ' ' . trim($systemInfo['OSArchitecture'] ?? '');
                $info['os_build'] = trim($systemInfo['Version'] ?? '未知') . ' (Build ' . trim($systemInfo['BuildNumber'] ?? '') . ')';
                $info['boot_time'] = trim($systemInfo['LastBootUpTime'] ?? '未知');
                $info['registered_user'] = trim($systemInfo['RegisteredUser'] ?? '未知');
                $info['serial_number'] = trim($systemInfo['SerialNumber'] ?? '未知');
                $info['manufacturer'] = trim($systemInfo['Manufacturer'] ?? '未知');
                $info['organization'] = trim($systemInfo['Organization'] ?? '未知');
                $info['install_date'] = trim($systemInfo['InstallDate'] ?? '未知');
                $info['local_time'] = trim($systemInfo['LocalDateTime'] ?? '未知');
                $info['process_count'] = intval($systemInfo['NumberOfProcesses'] ?? 0);
                $info['user_count'] = intval($systemInfo['NumberOfUsers'] ?? 0);

                // 内存使用情况
                $totalMemory = intval($systemInfo['TotalVisibleMemorySize'] ?? 0) / 1024;
                $freeMemory = intval($systemInfo['FreePhysicalMemory'] ?? 0) / 1024;
                $usedMemory = $totalMemory - $freeMemory;
                $info['memory_usage'] = [
                    'total' => round($totalMemory, 2) . ' GB',
                    'used' => round($usedMemory, 2) . ' GB',
                    'free' => round($freeMemory, 2) . ' GB',
                    'usage' => round(($usedMemory / $totalMemory) * 100, 2) . '%'
                ];

                // 虚拟内存使用情况
                $totalVirtual = intval($systemInfo['TotalVirtualMemorySize'] ?? 0) / 1024;
                $freeVirtual = intval($systemInfo['FreeVirtualMemory'] ?? 0) / 1024;
                $usedVirtual = $totalVirtual - $freeVirtual;
                $info['virtual_memory_usage'] = [
                    'total' => round($totalVirtual, 2) . ' GB',
                    'used' => round($usedVirtual, 2) . ' GB',
                    'free' => round($freeVirtual, 2) . ' GB',
                    'usage' => round(($usedVirtual / $totalVirtual) * 100, 2) . '%'
                ];
            }
        }

        return $info;
    }

    /**
     * 获取CPU架构信息
     */
    protected function getCpuArchitecture($Architecture): string
    {
        $architectureMap = [
            0 => 'x86',
            1 => 'MIPS',
            2 => 'Alpha',
            3 => 'PowerPC',
            5 => 'ARM',
            6 => 'ia64',
            9 => 'x64',
            12 => 'ARM64'
        ];

        return $architectureMap[$Architecture ?? 9] ?? '未知';
    }
}
